package com.example.drawproject.View;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

public class BaseSurfaceView extends SurfaceView implements SurfaceHolder.Callback,Runnable, View.OnTouchListener {

    private SurfaceHolder msurfaceholder;
    private Canvas mcanvas;
    private boolean isDrawing;
    private float touchX;
    private float touchY;

    public BaseSurfaceView(Context context) {
        super(context);
        init();
    }

    public BaseSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BaseSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void init() {
        msurfaceholder = getHolder();
        msurfaceholder.addCallback(this);

        setFocusable(true);
        setFocusableInTouchMode(true);
        this.setKeepScreenOn(true);


    }


    //创建
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        isDrawing = true;
        new Thread(this).start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {//改变

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {//销毁
        isDrawing = false;
    }

    @Override
    public void run() {
        while (isDrawing){
            drawing();
        }
    }
    public void drawing() {
        try {
            mcanvas = msurfaceholder.lockCanvas();
            //这里进行内容的绘制
        }finally {
            if (mcanvas != null){
                msurfaceholder.unlockCanvasAndPost(mcanvas);
            }
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        touchX = event.getX();
        touchY = event.getY();
        return false;
    }
}
